package cn.simon.controller;


import cn.simon.model.Users;
import cn.simon.service.UsersService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;

@Controller
@RequestMapping("userLogin")
public class UserLoginController {
    @Autowired
    private UsersService usersService;
    @GetMapping("login")
    public String addUsers(){
        return "userLogin";
    }
    @PostMapping("login")
    public String addUsers(HttpSession session, String username, String userPassword, String userPhone, Model model, String identifyCode) {

        //从session中取出验证码
        String sessionCode = (String)session.getAttribute("identifyFyCode");
        //验证码正确
        if (identifyCode.equalsIgnoreCase(sessionCode)){
            Users user = usersService.findByName(username);
            //对密码进行加密
            String password = DigestUtils.md5DigestAsHex(userPassword.getBytes());
            //判断用户名和密码
            if(user==null){
                model.addAttribute("msg","用户不存在");
                return "redirect:/userLogin";
            }
            if (userPassword.equals(password)){
                return "redirect:/index";
            }
        }else{
            String msg = "验证码错误";
            model.addAttribute("msg","验证码错误");
            //重定向到登录画面
            return "redirect:/userLogin";
        }
        return "redirect:/userRegister";
    }

    /**
     * 给前端返回一个验证码图片
     * @return
     */
    @RequestMapping("/identifyImage")
    public void identifyImage(HttpServletResponse response, HttpSession session){
       /* //创建随机验证码
        IdentifyCodeUtils utils = new IdentifyCodeUtils();
        String identifyCode = utils.getIdentifyCode();
        //session存入验证码
        session.setAttribute("identifyCode", identifyCode);
        //根据验证码创建图片
        BufferedImage identifyImage = utils.getIdentifyImage(identifyCode);
        //回传给前端
        utils.responseIdentifyImg(identifyImage,response);*/
    }
}
